package com.bruce.springai.service.impl;

import com.bruce.springai.service.VectorStoreService;
import jakarta.annotation.Resource;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.JsonReader;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class VectorStoreServiceImpl implements VectorStoreService {

    @Resource
    private VectorStore vectorStore ;

    @Value("bikes.json")
    private ClassPathResource sourceFile;

    @Override
    public boolean saveVector(String userId, String message) {
        vectorStore.add(List.of(new Document(message, Map.of("userId", userId))));
        return true;
    }

    @Override
    public boolean loadData() {
        JsonReader jsonReader = new JsonReader(sourceFile,
                "price", "name", "shortDescription", "description", "tags");
        List<Document> documents = jsonReader.get();
        this.vectorStore.add(documents);
        return true;
    }

    @Override
    public List<Document> ask(String question) {
        return vectorStore.similaritySearch(
                SearchRequest
                        .query(question)
                        .withTopK(5));
    }

    @Override
    public List<Document> getHistory(String userId, String message) {
        FilterExpressionBuilder expressionBuilder = new FilterExpressionBuilder();
        return vectorStore.similaritySearch(SearchRequest.query(message).withTopK(5).withFilterExpression(expressionBuilder.eq("userId", userId).build()));
    }
}
